package me.kany.project.spring.boot.config.activemq;

import javax.jms.MessageListener;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

/**
 * Created by Jason.Wang on 2016-07-18.
 */
@Configuration
public class JmsActiveMqConfig {

    /**
     * 创建ActiveMQConnectionFactory工厂的对象
     *
     * @return
     */
    @Bean(name = "targetConnectionFactory")
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL("tcp://localhost:61616");
        return activeMQConnectionFactory;
    }

    /**
     * 创建连接工厂
     *
     * @param targetConnectionFactory
     * @return
     */
    @Bean(name = "connectionFactory")
    public SingleConnectionFactory singleConnectionFactory(ActiveMQConnectionFactory targetConnectionFactory) {
        SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory();
        singleConnectionFactory.setTargetConnectionFactory(targetConnectionFactory);
        return singleConnectionFactory;
    }

    /**
     * 创建JmsTemplate的模版对象
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public JmsTemplate jmsTemplate(SingleConnectionFactory connectionFactory) {
        return new JmsTemplate(connectionFactory);
    }

    /**
     * 创建ActiveMQTopic对象
     *
     * @return
     */
    @Bean(name = "topicDestination")
    public ActiveMQTopic topicDestination() {
        ActiveMQTopic activeMQTopic = new ActiveMQTopic("me.kany.project.logcenter.topic");
        return activeMQTopic;
    }

    /**
     * @param connectionFactory
     * @param topicDestination
     * @param logMessageListener
     * @return
     */
    @Bean(name = "jmsContainer")
    public DefaultMessageListenerContainer defaultMessageListenerContainer(SingleConnectionFactory connectionFactory, ActiveMQTopic topicDestination, MessageListener logMessageListener) {
        DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
        defaultMessageListenerContainer.setConnectionFactory(connectionFactory);
        defaultMessageListenerContainer.setDestination(topicDestination);
        defaultMessageListenerContainer.setMessageListener(logMessageListener);
        return defaultMessageListenerContainer;
    }

}
